package com.service.purchase;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.InquiryMapper;
import com.dao.purchase.InquiryResultMapper;
import com.dao.purchase.PlanMmMapper;
import com.dao.purchase.ProgramMmMapper;
import com.dao.purchase.SupplyDealMapper;
import com.dao.purchase.SupplyDealMmMapper;
import com.dao.sys.FileDao;
import com.dao.sys.SysManageMapper;
import com.enums.BtnDbPermissionEnum;
import com.enums.SysModuleEnum;
import com.enums.WorkFlowIdModel;
import com.google.protobuf.ServiceException;
import com.model.external.oa.OaWorkFlowResult;
import com.model.purchase.PurchaseInquiry;
import com.model.purchase.PurchaseInquiryResult;
import com.model.purchase.PurchaseInquiryResultVO;
import com.model.purchase.PurchasePlanMm;
import com.model.purchase.PurchaseProgramMm;
import com.model.purchase.PurchaseSupplyDeal;
import com.model.purchase.PurchaseSupplyDealMm;
import com.model.sys.FileModel;
import com.model.sys.SysUser;
import com.service.external.oa.CreateResultService;
import com.service.external.oa.GetWFStatusService;
import com.service.sys.FileService;
import com.service.sys.SysDictService;
import com.service.sys.SysUserService;

/**
 * 询价结果
 * 
 * @author chenjun
 *
 */
@Service
public class ResultService {
	static final Logger logger = LoggerFactory.getLogger(ResultService.class);

	@Value("${filepath}")
	String filePathString;
	@Value("${server.url}")
	String serverUrlString;

	@Autowired
	InquiryResultMapper inquiryResultMapper;
	@Autowired
	CommonService commonService;
	@Autowired
	SupplyDealMapper supplyDealMapper;
	@Autowired
	SupplyDealMmMapper supplyDealMmMapper;
	@Autowired
	InquiryMapper inquiryMapper;
	@Autowired
	CreateResultService oaPurchaseService;
	@Autowired
	GetWFStatusService wfStatusService;
	@Autowired
	FileService fileService;
	@Autowired
	ProgramMmMapper programMmMapper;
	@Autowired
	FileDao fileDao;
	@Autowired
	SysDictService sysDictService;
	@Autowired
	SysManageMapper sysManageMapper;
	@Autowired
	SysUserService sysUserService;

	/**
	 * 询价结果详情
	 * 
	 * @param inqId
	 * @return
	 */
	public HttpResult selectResultInfo(String resId) {
		if (!StringUtils.isNotNull(resId)) {
			return HttpResult.error("参数不能为空!");
		}
		HttpResult httpResult = new HttpResult();
		PurchaseInquiryResultVO purchaseInquiryResultVO = inquiryResultMapper.selectVO(resId);
		if (purchaseInquiryResultVO != null) {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("resId", resId);
			// 成交供应商
			List<PurchaseSupplyDeal> purchaseSupplyDeals = supplyDealMapper.selectList(hashMap);
			purchaseInquiryResultVO.setPurchaseSupplyDeals(purchaseSupplyDeals);
			// 成交明细
			List<PurchaseSupplyDealMm> purchaseSupplyDealMms = supplyDealMmMapper.loadByResId(resId);
			purchaseInquiryResultVO.setPurchaseSupplyDealMms(purchaseSupplyDealMms);
		}
		logger.info("selectResultInfo:{}", purchaseInquiryResultVO);
		httpResult.setData(purchaseInquiryResultVO);
		return httpResult;
	}

	/**
	 * 询价结果详情
	 * 
	 * @param inqId
	 * @return
	 */
	public HttpResult selectResultMmInfo(String resId, String infId) {
		if (!StringUtils.isNotNull(resId) || !StringUtils.isNotNull(infId)) {
			return HttpResult.error("参数不能为空!");
		}
		HttpResult httpResult = new HttpResult();
		List<PurchaseSupplyDealMm> purchaseSupplyDealMm = supplyDealMmMapper.loadByInfIdAndResId(resId, infId);
		httpResult.setData(purchaseSupplyDealMm);
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void exportMmList(Map<String, Object> queryMap, HttpServletResponse response) {
		String resId = queryMap.get("resId").toString();
		String infId = queryMap.get("infId").toString();
		List<PurchaseSupplyDealMm> purchaseSupplyDealMm = supplyDealMmMapper.loadByInfIdAndResId(resId, infId);

		logger.info("exportMmList:{}", purchaseSupplyDealMm);

		try {
			EasyExcel.write(response.getOutputStream(), PurchaseSupplyDealMm.class).sheet("模板")
					.doWrite(purchaseSupplyDealMm);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	// 转交
	public HttpResult transfer(Map<String, Object> map) {
		HttpResult httpResult = new HttpResult();
		PurchaseInquiryResult inquiryResult = inquiryResultMapper.selectVO(map.get("resId").toString());
		inquiryResult.setInqActualId(map.get("inqActualId").toString());
		inquiryResult.setInqActualName(map.get("inqActualName").toString());
		inquiryResultMapper.update(inquiryResult);
		return httpResult;
	}

	/**
	 * 询价结果列表
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult selectResultList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();

		// 增加合同执行人查询判断，采购订单处使用
		if (queryMap.get("inqActualId") == null) {
			if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
				if (StringUtils.isNotNull(sysUser.getDatapermission())) {
					queryMap.put("deptIds", sysUser.getDatapermission().split(","));
				} else {
//					queryMap.put("createId", sysUser.getUserid());
					if (sysUser.getBtnPermission() != null
							&& sysUser.getBtnPermission().contains(BtnDbPermissionEnum.purchase.getValue())) {
						List<String> roleList = sysUserService.getPermissionFromModuleAndUser(sysUser.getUserid(),
								SysModuleEnum.InquiryResult.getValue());
						if (roleList != null && roleList.size() > 0) {
							queryMap.put("deptIds", roleList);
						}
					} else {
						queryMap.put("createId", sysUser.getUserid());
					}
				}

			}
		}
		List<PurchaseInquiryResult> list = inquiryResultMapper.selectList(queryMap);
		list = list.stream().sorted(Comparator.comparing(PurchaseInquiryResult::getResMoney,
				Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());
		int count = inquiryResultMapper.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectResultList:{}", list);

		return httpResult;
	}

	/**
	 * 保存询价结果
	 * 
	 * @param inquiryResultVO
	 * @return
	 * @throws ServiceException
	 * @throws RemoteException
	 */
	@Transactional
	public HttpResult saveResult(PurchaseInquiryResultVO inquiryResultVO) {
		if (inquiryResultVO == null || inquiryResultVO.getPurchaseSupplyDeals() == null) {
			return HttpResult.error("参数不能为空！");
		}
		if (!StringUtils.isNotNull(inquiryResultVO.getResUnit())) {
			return HttpResult.error("请选择中标供应商！");
		}
		if (inquiryResultVO.getResMoney() == null || inquiryResultVO.getResMoney().doubleValue() <= 0) {
			return HttpResult.error("中标金额不能为0！");
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();

		String resIdString = inquiryResultVO.getResId();
		if (!StringUtils.isNotNull(resIdString)) {
			String idString = UUID.randomUUID().toString();
			inquiryResultVO.setResId(idString);
			inquiryResultVO.setResCode(commonService.createCode("purchase_inquiry_result", "res_code"));
		}

		int result = 0;
		inquiryResultVO.setInqGroup(sysUser.getSap());

		// 成交表保存
		if (inquiryResultVO.getPurchaseSupplyDeals() != null) {
			for (PurchaseSupplyDeal purchaseSupplyDeal : inquiryResultVO.getPurchaseSupplyDeals()) {
				if (purchaseSupplyDeal.getInfNum() != null
						&& purchaseSupplyDeal.getInfNum().compareTo(BigDecimal.ZERO) != 0) {
					if (purchaseSupplyDeal.getInfTransportCost() != null) {
						purchaseSupplyDeal.setInfTransportPrice(purchaseSupplyDeal.getInfTransportCost()
								.divide(purchaseSupplyDeal.getInfNum(), 2, BigDecimal.ROUND_HALF_UP));
					}
					if (purchaseSupplyDeal.getInfLastTotalPrice() != null) {
						purchaseSupplyDeal.setInfUnitPrice(purchaseSupplyDeal.getInfLastTotalPrice()
								.divide(purchaseSupplyDeal.getInfNum(), 2, BigDecimal.ROUND_HALF_UP));
					}
				}
				purchaseSupplyDeal.setResCode1(inquiryResultVO.getResCode());
				purchaseSupplyDeal.setResId(inquiryResultVO.getResId());
				purchaseSupplyDeal.setStatus(inquiryResultVO.getStatus());
				if (supplyDealMapper.update(purchaseSupplyDeal) == 0) {
					purchaseSupplyDeal.setInqGroup(sysUser.getSap());
					purchaseSupplyDeal.setGramId(inquiryResultVO.getGramId());
					purchaseSupplyDeal.setInqIsContract(inquiryResultVO.getInqIsContract());
					purchaseSupplyDeal.setInqContractStart(inquiryResultVO.getInqContractStart());
					purchaseSupplyDeal.setInqContractEnd(inquiryResultVO.getInqContractEnd());
					purchaseSupplyDeal.setInqCurrency(inquiryResultVO.getInqCurrency());
					purchaseSupplyDeal.setInqName(inquiryResultVO.getInqName());
					supplyDealMapper.insert(purchaseSupplyDeal);
				}
			}
		}
		// 成交明细表保存
		for (PurchaseSupplyDealMm purchaseSupplyDealMm : inquiryResultVO.getPurchaseSupplyDealMms()) {
			purchaseSupplyDealMm.setResId(inquiryResultVO.getResId());
			purchaseSupplyDealMm.setStatus(inquiryResultVO.getStatus());
			purchaseSupplyDealMm.setResCode1(inquiryResultVO.getResCode());
			if (StringUtils.isNotNull(purchaseSupplyDealMm.getMmCode())) {
				// 最低价
				HashMap<String, Object> lowHashMap = new HashMap<String, Object>();
				lowHashMap.put("mmCode", purchaseSupplyDealMm.getMmCode());
				lowHashMap.put("sort", "dealUnitPrice");
				lowHashMap.put("order", "asc");
				lowHashMap.put("pageRows", 1);
				lowHashMap.put("pageNum", 0);
				lowHashMap.put("specialSql",
						"  deal_num>0 AND deal_unit_price>0 and res_id<>'" + purchaseSupplyDealMm.getResId() + "' ");
				List<PurchaseSupplyDealMm> lowDealMms = supplyDealMmMapper.selectList(lowHashMap);
				if (lowDealMms.size() == 1) {
					purchaseSupplyDealMm.setLowUnit(lowDealMms.get(0).getDealUnitPrice());
				}
				// 上次报价
				HashMap<String, Object> lastHashMap = new HashMap<String, Object>();
				lastHashMap.put("mmCode", purchaseSupplyDealMm.getMmCode());
				lastHashMap.put("pageRows", 1);
				lastHashMap.put("pageNum", 0);
				lastHashMap.put("specialSql",
						"  deal_num>0 AND deal_unit_price>0 and res_id<>'" + purchaseSupplyDealMm.getResId() + "' ");
				List<PurchaseSupplyDealMm> lastDealMms = supplyDealMmMapper.selectList(lastHashMap);
				if (lowDealMms.size() == 1) {
					purchaseSupplyDealMm.setLastUnit(lastDealMms.get(0).getDealUnitPrice());
				}
			}

			if (supplyDealMmMapper.update(purchaseSupplyDealMm) == 0) {
				purchaseSupplyDealMm.setGramId(inquiryResultVO.getGramId());
				supplyDealMmMapper.insert(purchaseSupplyDealMm);
			}
		}
		createOaFile(inquiryResultVO, resIdString);

		// 主表保存
		if (!StringUtils.isNotNull(resIdString)) {
			result = inquiryResultMapper.insert(inquiryResultVO);
		} else {
			result = inquiryResultMapper.update(inquiryResultVO);
		}
		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg(inquiryResultVO.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
			httpResult.setData(inquiryResultVO);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(inquiryResultVO.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * oa附件头
	 * 
	 * @param inquiryResultVO
	 * @return
	 */
	private List<List<String>> head(PurchaseInquiryResultVO inquiryResultVO) {
		List<List<String>> list = new ArrayList<List<String>>();
		List<String> head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("序号");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("请购单号");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("存货编码");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("存货名称");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("规格");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("品牌/型号");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("用途");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("计量单位");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("数量");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("需求公司");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("材料使用部门");
		list.add(head0);

		for (PurchaseSupplyDeal purchaseSupplyDeal : inquiryResultVO.getPurchaseSupplyDeals()) {
			List<String> head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("单价");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("金额");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("成交单价");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("成交金额");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("单价运费");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("运费");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("供应商联系人");
			list.add(head1);
			head1 = new ArrayList<String>();
			head1.add("询价结果");
			head1.add(purchaseSupplyDeal.getInfName());
			head1.add("联系方式");
			list.add(head1);
		}
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("最近成交价");
		list.add(head0);
		head0 = new ArrayList<String>();
		head0.add("询价结果");
		head0.add("最低成交价");
		list.add(head0);
		return list;
	}

	/**
	 * oa附件数据
	 * 
	 * @param inquiryResultVO
	 * @return
	 */
	private List<List<String>> data(PurchaseInquiryResultVO inquiryResultVO) {
		List<List<String>> list = new ArrayList<List<String>>();
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("gramId", inquiryResultVO.getGramId());
		List<PurchaseProgramMm> programMms = programMmMapper.selectProgramMmList(hashMap);
		int row = 0;
		BigDecimal lastunitDecimal = new BigDecimal(0);
		BigDecimal lowunitDecimal = new BigDecimal(0);
		for (PurchaseProgramMm programMm : programMms) {
			List<String> childList = new ArrayList<String>();
			childList.add(++row + "");
			childList.add(programMm.getPlanId());
			childList.add(programMm.getMmCode());
			childList.add(programMm.getMmDetail());
			childList.add("");
			childList.add("");
			childList.add("");
			childList.add(programMm.getMmUnit());
			childList.add(programMm.getGramPurNum() + "");
			childList.add(programMm.getPlanCorpName());
			childList.add(programMm.getPlanDeptName());
//			childList.add(programMm.getPlanIsContract());
//			childList.add(programMm)
			for (PurchaseSupplyDeal supplyDeal : inquiryResultVO.getPurchaseSupplyDeals()) {
				for (PurchaseSupplyDealMm supplyDealMm : inquiryResultVO.getPurchaseSupplyDealMms()) {
					if (supplyDealMm.getPlanId().equals(programMm.getPlanId())
							&& supplyDeal.getInfId().equals(supplyDealMm.getInfId())) {
						childList.add(supplyDealMm.getInqOfrUnitPrice() + "");
						childList.add(supplyDealMm.getInqOfrTotalPrice() + "");
						childList.add(
								supplyDealMm.getDealUnitPrice() == null ? "" : (supplyDealMm.getDealUnitPrice() + ""));
						childList.add(supplyDealMm.getDealTotalPrice() == null ? ""
								: (supplyDealMm.getDealTotalPrice() + ""));
						childList.add(supplyDealMm.getInqTransportUnitPrice() == null ? ""
								: (supplyDealMm.getInqTransportUnitPrice() + ""));
						childList.add(supplyDealMm.getInqTransportTotalPrice() == null ? ""
								: (supplyDealMm.getInqTransportTotalPrice() + ""));
						childList.add(supplyDeal.getInfContact());
						childList.add(supplyDeal.getInfContactTel());
						lastunitDecimal = supplyDealMm.getLastUnit();
						lowunitDecimal = supplyDealMm.getLowUnit();
						break;
					}
				}
			}
			childList.add(lastunitDecimal == null ? "" : (lastunitDecimal + ""));
			childList.add(lowunitDecimal == null ? "" : (lowunitDecimal + ""));
			list.add(childList);
		}
		return list;
	}

	private HttpResult saveFile(PurchaseInquiryResultVO inquiryResultVO, String resIdString) {
//		fileService.delete(inquiryResultVO.getResId());
		FileModel fileModel = new FileModel();
		String fileName = StringUtils.replaceBlank(inquiryResultVO.getGramName().trim());
		fileName += ".xlsx";
		fileModel.setFileName(fileName);
		fileModel.setFileId(inquiryResultVO.getResId());
		fileModel.setFileUrl(DateUtils.getCurrentYear() + DateUtils.getCurrentMonth());
		fileModel.setFileTable("purchase_inquiry_result");
		fileModel.setFileRow(inquiryResultVO.getResId());

		if (fileDao.update(fileModel) == 0) {
			fileDao.insert(fileModel);
		}

		return HttpResult.ok();
	}

	/**
	 * 生成oa附件
	 * 
	 * @param inquiryResultVO
	 * @return
	 */
	private HttpResult createOaFile(PurchaseInquiryResultVO inquiryResultVO, String resIdString) {
		String filePath = filePathString + "/" + DateUtils.getCurrentYear() + DateUtils.getCurrentMonth();
		String fileName = filePath + "/" + inquiryResultVO.getResId() + "-"
				+ StringUtils.replaceBlank(inquiryResultVO.getGramName()) + ".xlsx";

		File dir = new File(filePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		EasyExcel.write(fileName)
				// 这里放入动态头
				.head(head(inquiryResultVO)).sheet("询价结果")
				// 当然这里数据也可以用 List<List<String>> 去传入
				.doWrite(data(inquiryResultVO));
		HttpResult fileHttpResult = saveFile(inquiryResultVO, resIdString);
		if (fileHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
			return HttpResult.error();
		}
		return HttpResult.ok();
	}

	/**
	 * 提交询价结果
	 * 
	 * @param inquiryResultVO
	 * @return
	 */
	@Transactional
	public HttpResult commitResult(PurchaseInquiryResultVO inquiryResultVO) {
		if (inquiryResultVO == null || inquiryResultVO.getPurchaseSupplyDeals() == null) {
			return HttpResult.error("参数不能为空！");
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();

		if (!StringUtils.isNotNull(sysUser.getSap())) {
			return HttpResult.error("sap用户id不能为空!");
		}

		// 调用oa接口
//			HashMap<String, Object> dicHashMap = new HashMap<String, Object>();
//			dicHashMap.put("dicName", DictGlobal.oaPurchaseCheckParentNameString);
//			dicHashMap.put("query", DictGlobal.oaPurchaseCheckNameString);
//			List<SysDict> dicts = sysDictService.queryItemByTypeName(dicHashMap);
//			if (dicts != null && dicts.size() > 0) {
//				String valueString = dicts.get(0).getDicValue();
//				BigDecimal bigDecimal = new BigDecimal(valueString);
//				if (bigDecimal.compareTo(inquiryResultVO.getResMoney()) <= 0) {
		if (inquiryResultVO.getOaFlowId() == 0) {
			if (StringUtils.isNotNull(inquiryResultVO.getOaSubmit())
					&& inquiryResultVO.getOaSubmit().equals(Global.YES + "")) {
				HttpResult oaResult = oaPurchaseService.createInqueryResult(inquiryResultVO, sysUser.getWxid());
				if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(oaResult.getMsg());
				}
				OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
				inquiryResultVO.setOaFlowId(oaWorkFlowResult.getOaFlowId());
				inquiryResultVO.setOaSubmit(Global.NO + "");
			}
		} else {
			// 采购员保存时不调用oa，重复提交时第二次不调用oa
			if (StringUtils.isNotNull(inquiryResultVO.getOaSubmit())
					&& inquiryResultVO.getOaSubmit().equals(Global.YES + "")) {
				HttpResult oaResult = oaPurchaseService.submitInqueryResult(inquiryResultVO, sysUser.getWxid());
				if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(oaResult.getMsg());
				}
				inquiryResultVO.setOaSubmit(Global.NO + "");
			}
		}

		int result = 0;

		// 主表保存
		inquiryResultVO.setStatus(Global.YES + "");
		result = inquiryResultMapper.update(inquiryResultVO);

		// 成交表保存
		if (inquiryResultVO.getPurchaseSupplyDeals() != null) {
			for (PurchaseSupplyDeal purchaseSupplyDeal : inquiryResultVO.getPurchaseSupplyDeals()) {
				if (purchaseSupplyDeal.getInfNum() != null
						&& purchaseSupplyDeal.getInfNum().compareTo(BigDecimal.ZERO) != 0) {
					if (purchaseSupplyDeal.getInfTransportCost() != null) {
						purchaseSupplyDeal.setInfTransportPrice(purchaseSupplyDeal.getInfTransportCost()
								.divide(purchaseSupplyDeal.getInfNum(), 2, BigDecimal.ROUND_HALF_UP));
					}
					if (purchaseSupplyDeal.getInfLastTotalPrice() != null) {
						purchaseSupplyDeal.setInfUnitPrice(purchaseSupplyDeal.getInfLastTotalPrice()
								.divide(purchaseSupplyDeal.getInfNum(), 2, BigDecimal.ROUND_HALF_UP));
					}
				}
				purchaseSupplyDeal.setResId(inquiryResultVO.getResId());
				purchaseSupplyDeal.setStatus(Global.YES + "");
				if (supplyDealMapper.update(purchaseSupplyDeal) == 0) {
				}
				// 成交明细表保存
				for (PurchaseSupplyDealMm purchaseSupplyDealMm : inquiryResultVO.getPurchaseSupplyDealMms()) {
					purchaseSupplyDealMm.setStatus(Global.YES + "");
					purchaseSupplyDealMm.setResId(inquiryResultVO.getResId());
					if (supplyDealMmMapper.update(purchaseSupplyDealMm) == 0) {
					}
				}
			}
		}

		// 将询价书揭示状态改为已生成
		PurchaseInquiry inquiry = inquiryMapper.load(inquiryResultVO.getInqId());
		inquiry.setInqRevealStatus(Global.NUMERICAL_TWO + "");
		inquiryMapper.update(inquiry);

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("提交成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("提交失败！");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult commitAdmin(PurchaseInquiryResultVO inquiryResultVO) {
		if (inquiryResultVO == null) {
			return HttpResult.error("参数不能为空！");
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			return HttpResult.error("无权限");
		}

		int result = 0;
		// 成交表保存
		List<PurchaseSupplyDeal> supplyDeals = supplyDealMapper.loadByResId(inquiryResultVO.getResId());
		for (PurchaseSupplyDeal purchaseSupplyDeal : supplyDeals) {
			purchaseSupplyDeal.setStatus(Global.YES + "");
			if (supplyDealMapper.update(purchaseSupplyDeal) == 0) {
			}
		}
		// 成交明细表保存
		List<PurchaseSupplyDealMm> supplyDealMms = supplyDealMmMapper.loadByResId(inquiryResultVO.getResId());
		for (PurchaseSupplyDealMm purchaseSupplyDealMm : supplyDealMms) {
			purchaseSupplyDealMm.setStatus(Global.YES + "");
			if (supplyDealMmMapper.update(purchaseSupplyDealMm) == 0) {
			}
		}

		// 主表保存
		inquiryResultVO.setStatus(Global.YES + "");
		result = inquiryResultMapper.update(inquiryResultVO);

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("提交成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("提交失败！");
		}
		return httpResult;
	}

	/**
	 * 退回
	 * 
	 * @param purchasePlanMm
	 * @return
	 */
	@Transactional
	public HttpResult back(PurchaseInquiryResult resultModel) {
		if (resultModel == null) {
			return HttpResult.error("请求参数不能为空!");
		}

		SysUser sysUser = SpringMvcUtils.getSysUser();
		// oa退回才可撤回
		HttpResult httpResult = wfStatusService.getWorkflowRequestLogs(sysUser.getWxid(), WorkFlowIdModel.inquiryString,
				resultModel.getOaFlowId() + "");
		if (httpResult.getCode() != HttpStatus.SUCCESS_CODE) {
			return httpResult;
		}

		int result = 0;
		resultModel.setOaFlowId(0);
		resultModel.setStatus(Global.NO + "");
		result = inquiryResultMapper.update(resultModel);

		List<PurchaseSupplyDeal> supplyDeals = supplyDealMapper.loadByResId(resultModel.getResId());
		for (PurchaseSupplyDeal supplyDeal : supplyDeals) {
			supplyDeal.setStatus(Global.NO + "");
			result += supplyDealMapper.update(supplyDeal);
		}

		List<PurchaseSupplyDealMm> supplyDealMms = supplyDealMmMapper.loadByResId(resultModel.getResId());
		for (PurchaseSupplyDealMm supplyDealMm : supplyDealMms) {
			supplyDealMm.setStatus(Global.NO + "");
			result += supplyDealMmMapper.update(supplyDealMm);
		}

		if (result > 0) {
			return HttpResult.ok("回退成功");
		} else {
			return HttpResult.error("不存在此询价结果!");
		}
	}

	@Transactional
	public HttpResult backAdmin(PurchaseInquiryResult resultModel) {
		if (resultModel == null) {
			return HttpResult.error("请求参数不能为空!");
		}

		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			return HttpResult.error("无权限");
		}

		int result = 0;
		resultModel.setStatus(Global.NO + "");
//		resultModel.setOaFlowId(Global.NO);
		result = inquiryResultMapper.update(resultModel);

		List<PurchaseSupplyDeal> supplyDeals = supplyDealMapper.loadByResId(resultModel.getResId());
		for (PurchaseSupplyDeal supplyDeal : supplyDeals) {
			supplyDeal.setStatus(Global.NO + "");
			result += supplyDealMapper.update(supplyDeal);
		}

		List<PurchaseSupplyDealMm> supplyDealMms = supplyDealMmMapper.loadByResId(resultModel.getResId());
		for (PurchaseSupplyDealMm supplyDealMm : supplyDealMms) {
			supplyDealMm.setStatus(Global.NO + "");
			result += supplyDealMmMapper.update(supplyDealMm);
		}

		if (result > 0) {
			return HttpResult.ok("回退成功");
		} else {
			return HttpResult.error("不存在此询价结果!");
		}
	}

	/**
	 * 删除
	 *
	 * @param inqId
	 * @return
	 */
	@Transactional
	public HttpResult delResult(String resId) {
		if (!StringUtils.isNotNull(resId)) {
			return HttpResult.error("参数不能为空!");
		}
		PurchaseInquiryResult model = inquiryResultMapper.load(resId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = inquiryResultMapper.delete(resId);
		result += supplyDealMapper.deleteByResId(resId);
		result += supplyDealMmMapper.deleteByResId(resId);
		// 将询价书揭示状态改为已提交
		PurchaseInquiry inquiry = inquiryMapper.load(model.getInqId());
		inquiry.setInqRevealStatus(Global.YES + "");
		inquiryMapper.update(inquiry);

		if (result > 0) {
			httpResult.setMsg("删除成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条询价结果！");
		}
		return httpResult;
	}

	@Autowired
	PlanMmMapper planMapper;

	/**
	 * 删除物料结果表
	 * 
	 * @param resId
	 * @param infId
	 * @param planId
	 * @return
	 */
	@Transactional
	public HttpResult delResultMm(String resId, String infId, String planId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(resId)) {
			return HttpResult.error("参数不能为空!");
		}
		int result = supplyDealMmMapper.delete(resId, infId, planId);
//		PurchaseSupplyDealMm supplyDealMm = supplyDealMmMapper.load(infId, resId, planId);
		PurchasePlanMm plan = planMapper.load(planId);
//		if (plan.getPlanStockNum() != null && supplyDealMm.getDealNum() != null) {
//			BigDecimal stockDecimal = plan.getPlanStockNum().add(supplyDealMm.getDealNum());
//			plan.setPlanStockNum(stockDecimal);
//		}
		if (plan != null) {
			plan.setStatus(Global.YES + "");
			planMapper.update(plan);
		}
		if (result > 0) {
			httpResult.setMsg("删除成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条询价结果！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void exportList(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();

		// 增加合同执行人查询判断，采购订单处使用
		if (queryMap.get("inqActualId") == null) {
			if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
				if (StringUtils.isNotNull(sysUser.getDatapermission())) {
					queryMap.put("deptIds", sysUser.getDatapermission().split(","));
				} else {
//					queryMap.put("createId", sysUser.getUserid());
					if (sysUser.getBtnPermission() != null
							&& sysUser.getBtnPermission().contains(BtnDbPermissionEnum.purchase.getValue())) {
						List<String> roleList = sysUserService.getPermissionFromModuleAndUser(sysUser.getUserid(),
								SysModuleEnum.InquiryResult.getValue());
						if (roleList != null && roleList.size() > 0) {
							queryMap.put("deptIds", roleList);
						}
					} else {
						queryMap.put("createId", sysUser.getUserid());
					}
				}

			}
		}
		List<PurchaseInquiryResult> list = inquiryResultMapper.selectList(queryMap);

		logger.info("exportInquiryList:{}", list);

		try {
			EasyExcel.write(response.getOutputStream(), PurchaseInquiryResult.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
